import { useState, useRef, useCallback, useEffect } from "react";
import FeatureLayer from "@geoscene/core/layers/FeatureLayer";
import PictureMarkerSymbol from "@geoscene/core/symbols/PictureMarkerSymbol";
import SimpleRenderer from "@geoscene/core/renderers/SimpleRenderer";
import { cluster } from "@/utils/gis/Cluster";

interface IProps {
  url: string;
  iconUrl: string;
  type?: string;
  mapInstance: any;
  viewInstance: any;
  options?: {
    iconWidth?: number;
    iconHeight?: number;
    layerId?: string;
    visible?: boolean;
    outFields?: string[];
    definitionExpression?: string;
    popupTemplate?: any;
    onIconClick?: (feature: any) => void;
    onLayerLoad?: (layer: any) => void;
  };
}

/**
 * FeatureLayer管理Hook
 * @param {string} url - FeatureLayer服务URL
 * @param {string} iconUrl - 图标URL或Base64数据
 * @param {Object} mapInstance - 地图实例
 * @param {Object} options - 配置选项
 * @returns {Object} 图层状态和方法
 */
export const useFeatureLayer = ({
  url,
  iconUrl,
  type = "custom",
  mapInstance,
  viewInstance,
  options = {},
}: IProps) => {
  const {
    layerId = `${type}-feature-layer-${Date.now()}`,
    visible = true,
    outFields = ["*"],
    definitionExpression = "1=1",
    popupTemplate = null,
    onIconClick = null,
    onLayerLoad = null,
  } = options;

  // 状态管理
  const [isLoaded, setIsLoaded] = useState(false);
  const [isVisible, setIsVisible] = useState(visible);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<any>(null);

  const layerRef = useRef<any>(null);

  /**
   * 创建图标符号
   */
  const createSymbol = useCallback(() => {
    return new PictureMarkerSymbol({
      url: iconUrl,
      width: (options?.iconWidth || 24) + "px",
      height: (options?.iconHeight || 24) + "px",
    });
  }, [iconUrl, options]);

  /**
   * 加载图层
   */
  const loadLayer = useCallback(async () => {
    if (!url || !iconUrl) {
      setError("URL和iconUrl为必填参数");
      return;
    }

    if (!mapInstance || !viewInstance) {
      setError("地图实例未就绪");
      return;
    }

    if (layerRef.current && isLoaded) {
      showLayer();
      return;
    }

    setLoading(true);
    setError(null);

    try {
      // 创建图标符号和渲染器
      const symbol = createSymbol();
      const renderer = new SimpleRenderer({ symbol });

      // 创建FeatureLayer
      const layer = new FeatureLayer({
        url,
        id: layerId,
        outFields,
        definitionExpression,
        popupTemplate,
        renderer,
        visible: isVisible,
        featureReduction: cluster(),
      });

      // 监听图层加载
      await layer.load();

      // 添加到地图
      mapInstance.add(layer, 0);

      // @ts-ignore
      layer.on("click", (event: any) => {
        // 设置
        const feature = event.graphic;
        console.log(feature);

        onIconClick && onIconClick(feature);
      });

      // // 监听图标点击事件
      // viewInstance.on("click", (event: any) => {
      //     // 执行命中测试
      //     viewInstance.hitTest(event).then((response: any) => {
      //         if (response.results.length > 0) {
      //             const graphic = response.results[0].graphic;

      //             // 检查是否点击了FeatureLayer的要素
      //             if (graphic.layer && graphic.layer.id === layer.id) {
      //                 // 获取要素的完整属性数据
      //                 const featureAttributes = graphic.attributes;

      //                 // 处理并显示数据
      //                 console.log('featureAttributes', featureAttributes);
      //             }
      //         } else {
      //             // 没有点击到要素
      //             console.log('没有点击到要素');
      //         }
      //     });
      // });

      layerRef.current = layer;
      setIsLoaded(true);
      setLoading(false);

      // 触发加载回调
      if (onLayerLoad) {
        onLayerLoad(layer);
      }
    } catch (err) {
      setError(`图层加载失败: ${JSON.stringify(err)}`);
      setLoading(false);
    }
  }, [
    url,
    iconUrl,
    mapInstance,
    viewInstance,
    isLoaded,
    isVisible,
    createSymbol,
    onIconClick,
    onLayerLoad,
    layerId,
    outFields,
    definitionExpression,
    popupTemplate,
  ]);

  /**
   * 显示图层
   */
  const showLayer = useCallback(() => {
    if (layerRef.current) {
      layerRef.current.visible = true;
      setIsVisible(true);
    }
  }, []);

  /**
   * 隐藏图层
   */
  const hideLayer = useCallback(() => {
    if (layerRef.current) {
      layerRef.current.visible = false;
      setIsVisible(false);
    }
  }, []);

  /**
   * 卸载图层
   */
  const unloadLayer = useCallback(() => {
    if (layerRef.current && mapInstance) {
      mapInstance.remove(layerRef.current);
      layerRef.current.destroy();
      layerRef.current = null;
      setIsLoaded(false);
      setIsVisible(false);
    }
  }, [mapInstance]);

  /**
   * 切换图层显隐
   */
  const toggleLayer = useCallback(() => {
    if (!isLoaded) {
      loadLayer();
    } else {
      isVisible ? hideLayer() : showLayer();
    }
  }, [isLoaded, isVisible, loadLayer, showLayer, hideLayer]);

  // 清理效果
  useEffect(() => {
    return () => {
      if (layerRef.current) {
        unloadLayer();
      }
    };
  }, [unloadLayer]);

  return {
    // 状态
    layer: layerRef.current,
    isLoaded,
    isVisible,
    loading,
    error,

    // 方法
    loadLayer,
    showLayer,
    hideLayer,
    unloadLayer,
    toggleLayer,
  };
};
